﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WSPay.Application;
using WSPay.Common;
using WSPay.Domain;
using WSPay.Web.Areas.Manage.Models;

namespace WSPay.Web.Areas.Manage.Controllers
{
    public class ClientController : Controller
    {
        public IClientService ClientService
        {
            get; private set;
        }

        public ClientController(IClientService clientService)
        {
            ClientService = clientService;
        }
        // GET: Manage/Client
        public ActionResult Index(int? page)
        {
            const int pageSize = 20;
            var pageNumber = page ?? 1;

            var clientInfos = ClientService.ReadQuery();
             return View(clientInfos.ToPagedList(pageNumber - 1, pageSize));
        }

        public ActionResult Add()
        {
            var model = new ClientAddViewModel();
            model.Guid = Guid.NewGuid();
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Add(ClientAddViewModel model)
        {
            if (ModelState.IsValid)
            {   
                try
                {
                    var clinetInfo = new ClientInfo(model.Guid, model.Name, model.MD5Key);
                    ClientService.CreateClient(clinetInfo);
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var clientInfo = ClientService.GetByID(id);
            if (clientInfo == null) View("Error");

            return View(clientInfo);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(ClientEditViewModel model)
        {
            var clientInfo = ClientService.GetByID(model.ID);

            if (clientInfo == null) View("Error");

            clientInfo.Name = model.Name;
            clientInfo.MD5Key = model.MD5Key;

            try
            {
                ClientService.ChangeClient(clientInfo);

                return RedirectToAction("Index");

            }catch(Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }
            return View(clientInfo);
        }
    }
}